package tiepbm.app.util.hardware;


import tiepbm.app.util.Log;
import android.app.Activity;
import android.os.IBinder;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;

public class KeyboardUtil {

	
	private static boolean isShowKeyboard = false;
	
	/**
	 * Use to hide keyboard system
	 * 
	 * @param activity
	 */
	public static void hideSoftKeyboard(Activity activity) {
		InputMethodManager inputMethodManager = (InputMethodManager) activity
				.getSystemService(Activity.INPUT_METHOD_SERVICE);
		View view = activity.getCurrentFocus();
		if (view != null) {
			IBinder binder = view.getWindowToken();
			if (binder != null) {
				inputMethodManager.hideSoftInputFromWindow(binder, 0);
			}
		}

	}

	/**
	 * Check keyboard is show
	 * 
	 * @param activity
	 * 
	 * @return
	 */
	public static boolean isShowKeyboard(Activity activity) {

		final View rootView = activity.getWindow().getDecorView()
				.findViewById(android.R.id.content);
		final View rootViewActivity;
		if(rootView instanceof ViewGroup) {
			rootViewActivity = ((ViewGroup) rootView).getChildAt(0);
		} else {
			rootViewActivity = rootView;
		}
		
		rootViewActivity.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					@Override
					public void onGlobalLayout() {
						int heightDiff = rootViewActivity.getRootView().getHeight()
								- rootViewActivity.getHeight();
						if (heightDiff > 100) { // if more than 100 pixels, its
												// probably a keyboard...
							isShowKeyboard = true;
							Log.d("keyboard is showing");
						} else {
							isShowKeyboard = false;
							Log.d("keyboard hide");
						}
					}
				});
		
		return isShowKeyboard;
	}
}
